var express = require('express');
var router = express.Router();
var db=require("mongoose");
var schema=require("../mondels/users.js");
var users=db.model('users');
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.post('/',function(req,res) {//登陆；
    var username = req.body['username'],
        userpassword = req.body['password'];
    users.findOne({email: username, password: userpassword, condition: true}, function (err, docs) {
        if (err) {
            res.locals.error = "系统维护中";
            res.render('index');
        } else {
            if (docs == null) {
                res.locals.error = "用户名和密码不存在";
                res.render('index');
            } else {
                console.log(docs);
                res.render('coze',{title:"title",dc: docs});
            }
        }
    });
});

router.use("/register",function(req,res){//注册
    var email=req.body['username'];
    users.findOne({email:email},function(err,docs) {
        if(err){
            res.write('{"status":"407","message":"系统异常"}');
            res.end();
        }
        else
        {
            if(docs==null){
                var password=req.body['password'];
               var u=new users();
                u.email=email;
                u.password=password;
                var leth = Math.random() * 10 + 3;
                var newpass = 'w';
                for (var i = 0; i < leth; i++) {
                    newpass = newpass + (Math.random() * 10).toFixed(0);
                }
                u.auth=newpass;
                u.condition=false;
                u.save(function(err){
                    if(err){
                        res.write('{"status":"407","message":"注册失败了"}');
                        res.end();
                    }
                    else{
                        var info="?username="+email+"&auth="+newpass;
                        var mes = '<b>欢迎注册cose网页聊天工具</b><br><p>请点击下面链接激活账号：</p><a href="http://localhost:3000/activation'+info+'">点击此处激活</a>';
                        cosemailer(email, mes);

                        res.write('{"status":"200","message":"请登录你的邮箱，激活账号"}');
                        res.end();
                    }
                });


            }else {
                res.write('{"status":"407","message":"邮箱已经注册了"}');
                res.end();
            }
        }
    });

});


router.use("/verify",function(req,res){
   //验证
    var email=req.body['username'];
    users.findOne({email:email},function(err,docs) {
        if(err){
            res.write('{"status":"407","message":"系统异常"}');
            res.end();
        }
        else
        {
            console.log(docs);
            if(docs==null){
                res.write('{"status":"407","message":"邮箱可用"}');
                res.end();
            }else {
                res.write('{"status":"407","message":"邮箱已经注册了"}');
                res.end();
            }
        }
    });
});

router.use("/retrieve",function(req,res) {//找回密码
    var email=req.body['username'];

    users.findOne({email:email},function(err,docs) {
        if(err){
            res.write('{"status":"407","message":"系统异常"}');
            res.end();
        }
        else
        {
            if(docs==null){
                res.write('{"status":"407","message":"请确定你已经注册"}');
                res.end();
            }
            else {
                var leth = Math.random() * 10 + 3;
                var newpass = 'w';
                for (var i = 0; i < leth; i++) {
                    newpass = newpass + (Math.random() * 10).toFixed(0);
                }
                users.update({email: email}, {auth: newpass}, {multi: true}, function (err, numberAffected, raw) {
                    if (err) {
                        console.log(err);
                        res.write('{"status":"407","message":"请确认你的用户名正确"}');
                        res.end();
                    }
                    else {
                        var info="?username="+email+"&auth="+newpass;
                        var mes = '<b>欢迎注册cose网页聊天工具</b><br><p>请点击下面链接激活账号：</p><a href="http://localhost:3000/obtain'+info+'">点击此处激活</a>';
                        cosemailer(email, mes);
                        res.write('{"status":"200","message":"请登录你的邮箱，获取方法"}');
                        res.end();

                    }
                });
            }
        }
    });

});


router.use('/activation',function(req,res){//激活账户
    var email=req.query.username;
    var auth=req.query.auth;
users.findOne({email:email,auth:auth},function(err,docs) {
 if(err){
     res.write('系统异常');
     res.end();
 }else
 {
     if(docs==null){
         res.write('不存在这样的账号');
         res.end();
     }
     else
     {
         users.update({email: email}, {condition:true}, {multi: true}, function (err, numberAffected, raw) {
            if(err) {
                res.write('系统异常');
                res.end();
            }
         });
         res.render('userInfos');
     }
 }

});
});
router.use('/obtain',function(req,res){//获取设置新密码的权利；
    var email=req.query.username;
    var auth=req.query.auth;
    users.findOne({email:email,auth:auth},function(err,docs) {
        if(err){
            res.write('系统异常');
            res.end();
        }else {
            if (docs == null) {
                res.write('不存在这样的账号');
                res.end();
            }
            else {
                res.render('userInfos');
            }
        }});
});
function cosemailer(goal,content)
{
    var nodemailer = require('nodemailer');
    var transporter = nodemailer.createTransport({
        service: '126',
        auth: {
            user: 'kongmuo@126.com',
            pass: '982011687'
        }
    });
    var mailOptions = {
        from: 'Cose管理员<kongmuo@126.com>', // sender address
        to: goal, // list of receivers
        subject: 'cose', // Subject line
        text: 'cose验证', // plaintext body
        html: content // html body
    };
    transporter.sendMail(mailOptions, function(error, info){
        if(error){
            console.log(error);
            return false
        }else{
            console.log('Message sent: ' + info.response);
            return true;
        }
    });

}
module.exports = router;
